<template>
  <view class="brand-edit-container">
    <view class="form-content">
      <!-- 区域名称输入框 -->
      <view class="form-group">
        <text class="label">区域名称 *</text>
        <input 
          class="input-field" 
          v-model="formData.name" 
          placeholder="请输入区域名称" 
          placeholder-style="color: #999;"
          maxlength="50"
        />
      </view>
      
      <!-- 权重输入框 -->
      <view class="form-group">
        <text class="label">权重</text>
        <input 
          class="input-field" 
          v-model="formData.weigh" 
          placeholder="请输入权重（默认为0）" 
          placeholder-style="color: #999;"
          type="number"
        />
        <text class="form-hint">权重值越小，排序越靠前</text>
      </view>
      
      <!-- 提交按钮 -->
      <view class="submit-section">
        <button 
          class="submit-btn" 
          @click="submitForm" 
          :disabled="submitting"
        >
          {{ submitting ? '提交中...' : (isEditMode ? '保存修改' : '添加区域') }}
        </button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isEditMode: false,
      zoneId: '',
      submitting: false,
      formData: {
        name: '',
        weigh: 0
      }
    };
  },
  onLoad(options) {
    if (options.id) {
      this.isEditMode = true;
      this.zoneId = options.id;
      this.getZoneDetail();
    }
  },
  methods: {
    // 获取区域详情（用于编辑模式）
    async getZoneDetail() {
      try {
        uni.showLoading({
          title: '加载中...'
        });
        const res = await this.$request({
          url: '/table/zone/edit',
          method: 'GET',
          params: {
            ids: this.zoneId
          }
        });
        
        if (res.code === 1) {
          this.formData = {
            name: res.data.name || '',
            weigh: res.data.weigh || 0
          };
        } else {
          throw new Error(res.msg || '获取区域详情失败');
        }
      } catch (error) {
        console.error('获取区域详情失败:', error);
        uni.showToast({
          title: error.message || '获取区域详情失败',
          icon: 'none'
        });
        // 如果获取失败，返回上一页
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      } finally {
        uni.hideLoading();
      }
    },
    
    // 验证表单
    validateForm() {
      if (!this.formData.name || this.formData.name.trim() === '') {
        uni.showToast({
          title: '请输入区域名称',
          icon: 'none'
        });
        return false;
      }
      
      // 验证区域名称长度
      if (this.formData.name.length > 50) {
        uni.showToast({
          title: '区域名称不能超过50个字符',
          icon: 'none'
        });
        return false;
      }
      
      // 验证权重
      if (this.formData.weigh && (isNaN(this.formData.weigh) || parseInt(this.formData.weigh) < 0)) {
        uni.showToast({
          title: '权重必须是非负整数',
          icon: 'none'
        });
        return false;
      }
      
      return true;
    },
    
    // 提交表单
    async submitForm() {
      if (!this.validateForm()) {
        return;
      }
      
      try {
        this.submitting = true;
        
        // 构建请求参数
        const requestData = {
          name: this.formData.name.trim(),
          weigh: this.formData.weigh ? parseInt(this.formData.weigh) : 0
        };
        
        let url = '/table/zone/add';
        let successMsg = '添加成功';
        
        // 如果是编辑模式，添加id参数并使用编辑接口
        if (this.isEditMode) {
          url = '/table/zone/edit';
          successMsg = '编辑成功';
          requestData.ids = this.zoneId;
        }
        
        const res = await this.$request({
          url: url,
          method: 'POST',
          data: requestData
        });
        
        if (res.code === 1) {
          uni.showToast({
            title: successMsg,
            icon: 'success'
          });
          
          // 延迟返回列表页，让用户看到成功提示
          setTimeout(() => {
            if (this.isEditMode) {
              uni.navigateBack();
            } else {
              uni.navigateTo({
                url: '/pages/tablezone/index'
              });
            }
          }, 1500);
        } else {
          throw new Error(res.msg || (this.isEditMode ? '编辑失败' : '添加失败'));
        }
      } catch (error) {
        console.error(this.isEditMode ? '编辑区域失败:' : '添加区域失败:', error);
        uni.showToast({
          title: error.message || (this.isEditMode ? '编辑失败' : '添加失败'),
          icon: 'none'
        });
      } finally {
        this.submitting = false;
      }
    }
  }
};
</script>

<style scoped>
.brand-edit-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding: 30rpx;
}

.form-content {
  background-color: #fff;
  border-radius: 15rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.form-group {
  margin-bottom: 40rpx;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
}

.input-field {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #ddd;
  border-radius: 10rpx;
  padding: 0 25rpx;
  font-size: 28rpx;
  color: #333;
  background-color: #fff;
  box-sizing: border-box;
}

.form-hint {
  display: block;
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.submit-section {
  margin-top: 60rpx;
}

.submit-btn {
  width: 100%;
  height: 90rpx;
  background-color: #4cd964;
  color: #fff;
  border: none;
  border-radius: 15rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.submit-btn:disabled {
  background-color: #ccc;
  color: #fff;
}
</style>